import 'package:flutter/material.dart';
import 'package:mall/utils/alert/alert_util.dart';
import 'package:permission_handler/permission_handler.dart';

import 'device_info_util.dart';
import 'platform.dart';

class PermissionUtil {
  /// 相册权限
  static Future<bool> photoPermission(BuildContext context, {bool openSetting = true}) async {
    if (UtilPlatform.isAndroid) {
      var sdkInt = await DeviceInfoUtil.androidSDKInt();
      if (sdkInt <= 32 && context.mounted) {
        return await _handleStatus(context, permission: Permission.storage, openSetting: openSetting);
      }
    }

    if (context.mounted) {
      return await _handleStatus(context, permission: Permission.photos, openSetting: openSetting);
    }

    return false;
  }

  /// 相机权限
  static Future<bool> cameraPermission(BuildContext context, {bool openSetting = true}) async {
    return await _handleStatus(context, permission: Permission.camera, openSetting: openSetting);
  }

  /// 麦克风权限
  static Future<bool> microphonePermission(BuildContext context, {bool openSetting = true}) async {
    return await _handleStatus(context, permission: Permission.microphone, openSetting: openSetting);
  }

  /// 本地通知权限
  static Future<bool> notificationPermission(BuildContext context, {bool openSetting = true}) async {
    return await _handleStatus(context, permission: Permission.notification, openSetting: openSetting);
  }

  /// 打开App设置
  static Future<bool> openSetting() {
    return openAppSettings();
  }

  /// 自定义权限
  static Future<bool> customPermission( BuildContext context, {required Permission permission,bool openSetting = true,required String content}) async {
    return await _handleStatus(context,permission: permission, openSetting: openSetting,content: content);
  }

  // 授权处理
  static Future<bool> _handleStatus(
    BuildContext context, {
    required Permission permission,
    bool openSetting = true,
    String? content,
  }) async {
    var status = await permission.request();
    // 已授权
    if (status == PermissionStatus.granted) return true;

    // 未授权 - 不弹窗
    if (openSetting == false) return false;

    var contentStr = '';
    switch (permission) {
      case Permission.photos:
        contentStr = '请允许相册权限，以便使用头像更换、发送图片等功能。';
        break;
      case Permission.camera:
        contentStr = '请允许相机权限，以便使用头像更换、发送图片等功能。';
        break;
      case Permission.storage:
        contentStr = '请允许读取外部存储权限，以便使用头像更换、发送图片等功能。';
        break;
      case Permission.microphone:
        contentStr = '请允许麦克风权限，以便使用语音聊天，语音识别等功能。';
        break;
      case Permission.notification:
        contentStr = '请允许通知权限，以便使用消息提醒等功能。';
        break;
      default:
    }

    if (context.mounted) {
      AlertUtil.showAlert(context, content: content ?? contentStr, onConfirm: () => openAppSettings());
    }

    return false;
  }
}
